<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>Introspection</title>
<link rel="stylesheet" href="/cfg/format.css" type="text/css">
<meta http-equiv="content-type" content="text/html; charset=utf-8">
<meta name="keywords" content="Python, introspection, tutorial, programming language, learn Python">
<meta name="description" content="In this part of the Python tutorial,
we will mention introspection.">
<meta name="language" content="en">
<meta name="author" content="Jan Bodnar">
<meta name="distribution" content="global">

<script type="text/javascript" src="/lib/jquery.js"></script>
<script type="text/javascript" src="/lib/common.js"></script>

</head>

<body>

<div class="container">

<div id="wide_ad" class="ltow">
<script type="text/javascript"><!--
google_ad_client = "pub-9706709751191532";
/* 160x600, August 2011 */
google_ad_slot = "2484182563";
google_ad_width = 160;
google_ad_height = 600;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script>
</div>

<div class="content">

<a href="/" title="Home">Home</a>&nbsp;
<a href="..">Contents</a>


<h1>Introspection</h1>

<p>
In this part of the Python programming tutorial, we will talk about introspection. 
</p>

<script type="text/javascript"><!--
google_ad_client = "pub-9706709751191532";
/* NewSquare */
google_ad_slot = "0364418177";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script> 
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js"> 
</script> 

<p>
<b>Introspection</b> is an act of self examination. In computer programming, 
introspection is the ability to determine the type of an object at runtime. 
Python programming language has a large support of introspection. 
Everything in Python is an object. Every object in Python may have attributes 
and methods. By using introspection, we can dynamically inspect Python objects. 
</p>

<h2>The dir() function</h2>

<p>
The <code>dir()</code> function is the most important function when doing introspection. 
The function returns a sorted list of attributes and methods belonging to an object. 
</p>


<pre class="code">
>>> dir(())
['__add__', '__class__', '__contains__', '__delattr__', '__doc__', '__eq__', 
'__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', 
'__getslice__', '__gt__', '__hash__', '__init__', '__iter__', '__le__', 
'__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', 
'__reduce_ex__', '__repr__', '__rmul__', '__setattr__', '__sizeof__', 
'__str__', '__subclasshook__', 'count', 'index']
</pre>

<p>
Here we see an output of the dir() function for a tuple object. 
</p>

<pre class="code">
>>> print ().__doc__
tuple() -> empty tuple
tuple(iterable) -> tuple initialized from iterable's items

If the argument is a tuple, the return value is the same object.
</pre>

<p>
Our investigation showed, that there is a <code>__doc__</code> attribute for a tuple object. 
</p>

<pre class="code">
#!/usr/bin/python

# dir.py

import sys

class Object:
   def __init__(self):
      pass
   def examine(self):
      print self


o = Object()

print dir(o)
print dir([])
print dir({})
print dir(1)
print dir()
print dir(len)
print dir(sys)
print dir("String")
</pre>

<p>
The example examines several objects using the dir() function. A user defined object, 
native data types, a function, a string or a number. 
</p>

<hr class="btm">

<p>
Without any argument, the <code>dir()</code> returns names in the current scope.
</p>

<pre class="code">
>>> dir()
['__builtins__', '__doc__', '__name__', '__package__']
>>> import sys
>>> import math, os
>>> dir()
['__builtins__', '__doc__', '__name__', '__package__', 'math', 'os', 'sys']
</pre>

<p>
We execute the <code>dir()</code> function before and after we include some
modules. 
</p>

<h2>The type(), id() functions</h2>

<p>
The <code>type()</code> function returns the type of an object. 
</p>

<pre class="code">
#!/usr/bin/python

# types.py

import sys


def function(): pass

class MyObject():
   def __init__(self):
      pass

o = MyObject()

print type(1)
print type("")
print type([])
print type({})
print type(())
print type(object)
print type(function)
print type(MyObject)
print type(o)
print type(sys)
</pre>

<p>
The example print various types of objects to the console screen. 
</p>

<pre>
$ ./types.py 
&lt;type 'int'&gt;
&lt;type 'str'&gt;
&lt;type 'list'&gt;
&lt;type 'dict'&gt;
&lt;type 'tuple'&gt;
&lt;type 'type'&gt;
&lt;type 'function'&gt;
&lt;type 'classobj'&gt;
&lt;type 'instance'&gt;
&lt;type 'module'&gt;
</pre>

<p>
Output of the types.py script. 
</p>

<hr class="btm">

<p>
The <code>id()</code> returns a special id of an object. 
</p>

<pre class="code">
#!/usr/bin/python

# ids.py

import sys

def fun(): pass

class MyObject():
   def __init__(self):
      pass

o = MyObject()

print id(1)
print id("")
print id({})
print id([])
print id(sys)
print id(fun)
print id(MyObject)
print id(o)
print id(object)
</pre>

<p>
The code example prints ids of various objects. Both built-in and custom. 
</p>

<pre>
$ ./ids.py 
135717024
3084304536
3084111220
3084104940
3084304500
3084112812
3084074556
3084130444
135568640
</pre>


<h2>The sys module</h2>

<p>
The <code>sys</code> module provides access to system specific variables and 
functions used or maintained by the interpreter and to functions that 
interact strongly with the interpreter. The module allows us to query about
the Python environment. 
</p>

<pre class="code">
>>> import sys
>>> sys.version
'2.7.2+ (default, Oct  4 2011, 20:03:08) \n[GCC 4.6.1]'
>>> sys.platform
'linux2'
>>> sys.path
['', '/usr/lib/python2.7', '/usr/lib/python2.7/plat-linux2', 
'/usr/lib/python2.7/lib-tk', '/usr/lib/python2.7/lib-old', 
'/usr/lib/python2.7/lib-dynload', '/usr/local/lib/python2.7/dist-packages', 
'/usr/lib/python2.7/dist-packages', '/usr/lib/python2.7/dist-packages/PIL', 
'/usr/lib/python2.7/dist-packages/gst-0.10', '/usr/lib/python2.7/dist-packages/gtk-2.0', 
'/usr/lib/python2.7/dist-packages/ubuntu-sso-client']
</pre>

<p>
In the above code we examine the Python version, platform and search path locations.
</p>


<hr class="btm">

<p>
We will have another four variables of the <code>sys</code> module. We can use the
<code>dir()</code> function to get a full list of variables and functions of the
<code>sys</code> module.
</p>

<pre class="code">
>>> sys.maxint
2147483647
>>> sys.executable
'/usr/bin/python'
>>> sys.argv
['']
>>> sys.byteorder
'little'
</pre>

<p>
The example presents maxint, executable, argv and byteorder attributes of the
<code>sys</code> module. 
</p>

<pre class="explanation">
>>> sys.maxint
2147483647
</pre>

<p>
The maxint is the largest positive integer supported by Python's regular integer type.
</p>

<pre class="explanation">
>>> sys.executable
'/usr/bin/python'
</pre>

<p>
The executable is a string giving the name of the executable binary for 
the Python interpreter, on systems where this makes sense.
</p>

<pre class="explanation">
>>> sys.argv
['']
</pre>

<p>
This gives a list of command line arguments passed to a Python script. 
</p>

<pre class="explanation">
>>> sys.byteorder
'little'
</pre>

<p>
The byteorder is an indicator of the native byte order. This will have 
the value 'big' on big-endian (most-significant byte first) platforms, 
and 'little' on little-endian (least-significant byte first) platforms.
</p>


<h2>Various</h2>

<p>
Next we will show various other ways of inspecting our objects. 
</p>


<pre class="code">
#!/usr/bin/python

# attr.py

def fun(): pass


print hasattr(object, '__doc__')
print hasattr(fun, '__doc__')
print hasattr(fun, '__call__')

print getattr(object, '__doc__')
print getattr(fun, '__doc__')
</pre>

<p>
The <code>hasattr()</code> function checks, if an object has an attribute. 
The <code>getattr()</code> function returns the contents of an attribute, if there are some. 
</p>

<pre>
$ ./attr.py 
True
True
True
The most base type
None
</pre>

<p>
The <code>isinstance</code> function checks, if an objects is an instance 
of a specific class. 
</p>

<pre>
>>> print isinstance.__doc__
isinstance(object, class-or-type-or-tuple) -> bool

Return whether an object is an instance of a class or of a subclass thereof.
With a type as second argument, return whether that is the object's type.
The form using a tuple, isinstance(x, (A, B, ...)), is a shortcut for
isinstance(x, A) or isinstance(x, B) or ... (etc.).
</pre>

<p>
We can get the describtion of a function interactively. 
</p>


<pre class="code">
#!/usr/bin/python

# instance.py


class MyObject():
   def __init__(self):
      pass

o = MyObject()

print isinstance(o, MyObject)
print isinstance(o, object)
print isinstance(2, int)
print isinstance('str', str)
</pre>

<p>
As we know, everything is an object in Python. Even numbers or strings. 
The <code>object</code> is a base type of all objects in Python. 
That is why isinstance(o, object) returns True.
</p>

<pre>
$ ./instance.py 
True
True
True
True
</pre>

<p>
The <code>issubclass()</code> function checks, if a specific class 
is a derived class of another class. 
</p>

<pre class="code">
#!/usr/bin/python

# subclass.py

class Object():
   def __init__(self):
      pass

class Wall(Object):
   def __init__(self):
      pass

print issubclass(Object, Object)
print issubclass(Object, Wall)
print issubclass(Wall, Object)
print issubclass(Wall, Wall)
</pre>

<p>
In our code example, the Wall class is a subclass of the Object class.
Interestingly, Object and Wall are subclasses of themselves.
The Object class is not a subclass of class Wall. 
</p>

<pre>
$ ./subclass.py 
True
False
True
True
</pre>

<p>
The <code>__doc__</code> attribute gives some documentation about 
an object and the <code>__name__</code> attribute holds the name of the object. 
</p>

<pre class="code">
#!/usr/bin/python

# namedoc.py

def noaction():
   '''A function, which does nothing'''
   pass


funcs = [noaction, len, str]

for i in funcs:
   print i.__name__
   print i.__doc__
   print "-" * 75
</pre>


<p>
In our example, we crete a list of three functions. One custom and two native. 
We go through the list and print the __name__ and the __doc__ attributes. 
</p>

<pre>
$ ./namedoc.py
noaction
A function, which does nothing
---------------------------------------------------------------------------
len
len(object) -> integer

Return the number of items of a sequence or mapping.
---------------------------------------------------------------------------
str
str(object) -> string

Return a nice string representation of the object.
If the argument is a string, the return value is the same object.
---------------------------------------------------------------------------
</pre>

<p>
Output.
</p>


<p>
Finally, there is also a <code>callable()</code> function. The 
function checks, if an object is a callable object. Or in other words, 
if an object is a function. 
</p>

<pre class="code">
#!/usr/bin/python

# callable.py

class Car:
      
    def setName(self, name):
        self.name = name    

def fun():
    pass

c = Car()    
    
print callable(fun)
print callable(c.setName)
print callable([])
print callable(1)
</pre>

<p>
In the code example we check if three objects are callables.
</p>

<pre class="explanation">
print callable(fun)
print callable(c.setName)
</pre>

<p>
The fun() function and the setName() method are callables. (A method is a function
bound to an object.)
</p>

<pre>
$ ./callable.py
True
True
False
False
</pre>


<p>
In this part of the Python tutorial, we have talked about introspection in Python.
More tools for doing introspection can be found in the <code>inspect</code> module. 
</p>



<div class="botNav, center">
<span class="botNavItem"><a href="/">Home</a></span> ‡ <span class="botNavItem"><a href="..">Contents</a></span> ‡ 
<span class="botNavItem"><a href="#">Top of Page</a></span>
</div>


<div class="footer">
<div class="signature">
<a href="/">ZetCode</a> last modified December 18, 2012  <span class="copyright">&copy; 2007 - 2013 Jan Bodnar</span>
</div>
</div>

</div>  <!-- content -->

</div>  <!-- container -->

</body>
</html>
